import React, { useContext, useEffect, useRef, useState } from 'react'
import { Context } from '../App'

export default function TodoItem({ item }) {
  const { delTodo, changeDone, changeName } = useContext(Context)
  const [current, setCurrent] = useState({
    id: '',
    name: '',
  })
  const inputRef = useRef(null)

  //输入框的内容
  const showEdit = ({ id, name }) => {
    setCurrent({
      id,
      name,
    })
  }

  //给输入框添加光标
  useEffect(() => {
    inputRef.current.focus()
  }, [current])

  //双击后修改输入框的内容
  const onChangeName = (e) => {
    if (e.keyCode === 27) {
      setCurrent({ id: '', name: '' })
    }
    if (e.keyCode === 13) {
      //修改
      changeName(current.id, current.name)
      setCurrent({ id: '', name: '' })
    }
  }

  return (
    <li
      key={item.id}
      className={[
        item.done ? 'completed' : '',
        item.id === current.id ? 'editing' : '',
      ].join(' ')}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => changeDone(item.id)}
        />
        <label onDoubleClick={() => showEdit(item)}>{item.name}</label>
        <button className='destroy' onClick={() => delTodo(item.id)} />
      </div>
      <input
        className='edit'
        value={current.name}
        ref={inputRef}
        onBlur={() => setCurrent({ id: '', name: '' })}
        onChange={(e) => setCurrent({ ...current, name: e.target.value })}
        onKeyUp={onChangeName}
      />
    </li>
  )
}
